/**
 * commit列表中每项
 * @param {object} commitInfo 接口返回的commit对象
 * @param {boolean} condensed [默认为false] 使用浓缩版，不带Notice组件（背景色）、头像、间距更小，在compare、cr等commit列表中使用
 * @param {boolean} useForList [默认为false] 在列表页用，右侧为按钮组，且无背景色
 * @param {jsx} additionalRightItem [默认为null] 右侧提供一个额外槽位，可用来塞「测试结果」等按钮
 * @param {string} resourcePath [默认为null] 若传此参数，则浏览文件按钮不是跳到文件列表，而是跳到这个文件
 * @param {boolean} noBuildTag  默认false，true：表示不用展示扫描结果
 */

import React from 'react';
import PropTypes from 'prop-types';
import utils from 'utils';
import UsersAvatar from '@alife/teamix-at-users-avatar';
import CommitIdAndSrcBtns from '../commitIdAndSrcBtns';
import BuildsResultTag from 'components/buildsResultTag';
import GpgTag from 'components/gpgTag';
import { Balloon } from '@teamix/ui';
import { Link, navigate } from 'utils/router';
import { YunxiaoIcon, YunxiaoList, Title } from '@alife/devops-ui';
import dayjs from 'dayjs';
import exceed from 'utils/apimap';
import 'components/common/index.scss';
import Cover from 'atComponents/Cover';
import locale from 'utils/locale.js';
import './index.scss';
import intl from '../../locale';

const { pathResource } = window.FORCE;
export default class CommitInfoMedia extends React.PureComponent {
  static propTypes = {
    projectInfo: PropTypes.object,
    commitInfo: PropTypes.object,
    additionalRightItem: PropTypes.elementType,
    isSrcBtnShow: PropTypes.bool,
    useForList: PropTypes.bool, // 是否在列表中使用（无背景色等区别）
    noCover: PropTypes.bool, // 是否在列表中使用（无背景色等区别）
    isNeedRestart: PropTypes.bool, // 是否需要重新触发按钮，在MR和提交列表页第一个需要此按钮
    noBuildTag: PropTypes.bool,
    trackPage: PropTypes.string,
  };

  static defaultProps = {
    projectInfo: {},
    commitInfo: {},
    additionalRightItem: null,
    isSrcBtnShow: false,
    useForList: false,
    noCover: false,
    isNeedRestart: false,
    noBuildTag: false,
    trackPage: '',
  };

  constructor(props) {
    super(props);

    this.state = {
      isMsgDescVisible: false, // 提交信息的描述部分（即第一个换行符后的部分）默认隐藏，点...展开
      idLink: [],
    };
  }

  // commitinfo.id变化则将builds清空
  // componentWillReceiveProps(nextProps) {
  //   if (nextProps.commitInfo.id !== this.props.commitInfo.id) {
  //     this.setState({
  //       builds: [],
  //     });
  //   }
  // }
  componentDidMount() {
    // this.getCommitMsgDescArray();
  }

  componentDidUpdate(preProps) {
    const { commitInfo } = this.props;
    if (commitInfo.message !== preProps.commitInfo.message) {
      this.getCommitMsgDescArray();
    }
  }

  getCommitMsgDescArray = () => {
    const { commitInfo } = this.props;
    const commitMessage = commitInfo.message || commitInfo.title || '';
    const commitMessageArr = commitMessage.split('\n');
    const [, ...commitMessageDesc] = commitMessageArr;
    this.commitMessageDescHander(commitMessageDesc);
  };

  commitMessageDescHander = (data) => {
    let str = '';
    data.length > 0 &&
      data.map((va) => {
        for (let i = 0, num = Infinity; i < va.length; i++) {
          if (va[i] === '#') {
            num = i;
            str += ',';
          } else if (i > num) {
            str += va[i];
          }
        }
        return va;
      });
    // 提取与#拼接的值，并去重，同时限制并发请求数量
    let strData = null;
    if (str && str.length > 0) {
      const temp = {};
      strData = str
        .split(',')
        .filter((val) => {
          if (val) {
            if (temp[val]) return false;
            temp[val] = 1;
            return true;
          }
          return false;
        })
        .slice(0, 10);
    }
    this.commitIdHerfHander(strData);
  };

  commitIdHerfHander = async (data) => {
    if (!data) return false;
    const allRequest =
      data &&
      data.length > 0 &&
      data.map(async (va) => {
        const res = await exceed.fetch({
          api: 'project_commit_info_media_id_herf',
          params: { idList: va },
        });
        return res;
      });
    const result = await Promise.all(allRequest);
    const value = data.map((va, ids) => {
      return { id: va, data: result[ids].result };
    });
    this.setState({
      idLink: value,
    });
  };

  idlinkHander = (data) => {
    const { idLink } = this.state;
    const resArr =
      Array.isArray(data) &&
      data.length > 0 &&
      data.map((item) => {
        const splitArr = item.split(' ');
        return splitArr.map((v) => {
          if (v.indexOf('#') === -1) return v;
          const urlSplit = v.split('#');
          for (let i = 1; i < urlSplit.length; i += 1) {
            const flag =
              Array.isArray(idLink) &&
              idLink.length > 0 &&
              idLink.find((va) => va.id === urlSplit[i]);
            if (flag && flag.data?.length > 0) {
              urlSplit[i] = (
                <a
                  href={`${window.config.tbHost}/task/${flag.data[0]._id}`}
                  target="_blank"
                  rel="noreferrer"
                  style={{ paddingRight: 5 }}
                >
                  #{urlSplit[i]}
                </a>
              );
            } else {
              urlSplit[i] = <span>#{urlSplit[i]}</span>;
            }
          }
          return urlSplit;
        });
      });
    return (
      <div className="commit-msg-desc">
        {Array.isArray(resArr) &&
          resArr.map((v) => {
            return (
              <div className="commit-msg-desc-item" style={{ marginRight: '3px' }}>
                {v.map((va) => (
                  <span style={{ marginRight: '4px' }}>{va}</span>
                ))}
              </div>
            );
          })}
      </div>
    );
  };

  showCommitMsgDesc = () => {
    const { isMsgDescVisible, idLink } = this.state;
    if (!isMsgDescVisible && idLink.length <= 0) {
      this.getCommitMsgDescArray();
    }
    this.setState({
      isMsgDescVisible: !this.state.isMsgDescVisible,
    });
  };

  getAuthors = () => {
    const { commitInfo } = this.props;
    const { committer, author, author_name, committer_name, author_email, committer_email } =
      commitInfo;
    const arr = [];

    // TODO 主页跳转先不加
    arr.push({
      id: author ? author.id : '',
      name: author ? author.name : author_name || '',
      href: '',
      avatarUrl: author ? author.avatar_url : '',
    });

    if (
      committer_email &&
      author_email !== committer_email &&
      committer_email !== 'code@codeup.teambition.com'
    ) {
      arr.push({
        id: committer ? committer.id : '',
        name: committer ? committer.name : committer_name || '',
        href: '',
        avatarUrl: commitInfo ? commitInfo.avatar_url : '',
      });
    }
    arr.forEach((item) => {
      if (item.avatar_url) item.avatarUrl = item.avatar_url;
    });

    let authorsTxt = '';
    const fName = arr[0].name;
    const lName = arr[1] ? arr[1].name : '';
    authorsTxt = arr[1]
      ? intl.get(
          {
            id: 'code-assets.components.commitInfoMedia.content.FnameAuthorAndLname',
            defaultMessage: '{fName}(作者)和{lName}',
          },
          { fName, lName },
        )
      : fName;
    return { authorsTxt, authors: arr };
  };

  gotoCommitDetailFromCount = () => {
    const branchValue = window.location?.pathname?.split('/').filter((v) => v);
    const branch = branchValue && branchValue[branchValue.length - 1];
    const url = `/${pathResource.fullPath}/commit/${this.props.commitInfo.id}?branch=${branch}&anchor=bottom`;
    navigate(url);
  };

  render() {
    const {
      commitInfo,
      resourcePath,
      additionalRightItem,
      isSrcBtnShow,
      useForList,
      isNeedRestart,
      noBuildTag,
      trackPage,
      projectInfo,
      noCover,
      showCommentNum,
    } = this.props;
    const branchValue = window.location?.pathname?.split('/').filter((v) => v);
    const branch = branchValue && branchValue[branchValue.length - 1];
    if (!(commitInfo && Object.keys(commitInfo).length)) {
      return null;
    }
    const commitMessage = commitInfo.message || commitInfo.title || '';
    const commitMessageArr = commitMessage.split('\n');
    const [commitMessageTitle, ...commitMessageDesc] = commitMessageArr;

    // 有大量的commit是以一个换行符结尾的，隐刺对仅有一个换行符，且以其结尾的情况做兼容，不认为这种情况应展示 desc
    let hasCommitMessageDesc;
    if (
      commitMessageDesc.length &&
      !(commitMessageDesc.length === 1 && commitMessageDesc[0] === '')
    ) {
      hasCommitMessageDesc = true;
    }
    const { authors, authorsTxt } = this.getAuthors();
    return (
      <>
        <YunxiaoList.Item
          className={`commit-wrapper ${useForList ? 'use-for-list' : 'use-for-card'}`}
          cover={
            !useForList && !noCover ? (
              <Cover
                img={
                  'https://img.alicdn.com/imgextra/i1/O1CN01Zg8Nky1MK78OdE56g_!!6000000001415-2-tps-72-72.png'
                }
                style={{ marginRight: 20 }}
              />
            ) : null
          }
          title={
            <>
              <div className="commit-msg-title">
                <Link
                  to={`/${pathResource.fullPath}/commit/${this.props.commitInfo.id}?branch=${branch}`}
                  className="text-black"
                >
                  {commitMessageTitle}
                </Link>
                {hasCommitMessageDesc ? (
                  <span
                    className="commit-msg-desc-trigger show-more-span bright"
                    onClick={this.showCommitMsgDesc}
                  >
                    <YunxiaoIcon type="more-line" className="show-more-icon" size="small" />
                  </span>
                ) : null}
                {!useForList && !noBuildTag && (
                  <BuildsResultTag
                    container={{
                      target: 'commit', // 可选值为 commit 和 merge_request
                      id: commitInfo.id, // commit 或 merge_request 的 id
                    }}
                    projectInfo={projectInfo}
                    isNeedRestart={isNeedRestart}
                    size={'small'}
                  />
                )}
              </div>
              {/* {hasCommitMessageDesc && this.state.isMsgDescVisible ? (
                <div className="commit-msg-desc">
                  {commitMessageDesc.map((item) => (
                    <div className="commit-msg-desc-item">{item}</div>
                  ))}
                </div>
              ) : null} */}
              {hasCommitMessageDesc && this.state.isMsgDescVisible
                ? this.idlinkHander(commitMessageDesc)
                : null}
            </>
          }
          description={
            <div className="commit-msg-userinfo">
              <span>
                <UsersAvatar
                  dataSource={authors}
                  size="xs"
                  borderColor={useForList ? '#fff' : '#f7f7f7'}
                />
              </span>
              <span className="commit-user-info small">
                <span className="user-name">
                  <Title trigger={<span>{authorsTxt}</span>}>{authorsTxt}</Title>
                </span>

                <span className="user-action-des">
                  {
                    locale[
                      `file_commit_${
                        utils.isInOneHour(commitInfo.created_at || commitInfo.authored_date)
                          ? 'no_'
                          : ''
                      }at`
                    ]
                  }

                  <Balloon.Tooltip
                    align="t"
                    trigger={utils
                      .getBeautyTime(commitInfo.created_at || commitInfo.authored_date)
                      .toLowerCase()}
                  >
                    {dayjs(commitInfo.created_at || commitInfo.authored_date).format(
                      'YYYY-MM-DD HH:mm:ss',
                    )}
                  </Balloon.Tooltip>
                </span>
              </span>
            </div>
          }
          extra={
            <>
              {!showCommentNum && useForList && !noBuildTag && (
                <YunxiaoList.Item.Actions width="260px">
                  <BuildsResultTag
                    container={{
                      target: 'commit', // 可选值为 commit 和 merge_request
                      id: commitInfo.id, // commit 或 merge_request 的 id
                    }}
                    projectInfo={projectInfo}
                    isNeedRestart={isNeedRestart}
                    size={'medium'}
                  />
                </YunxiaoList.Item.Actions>
              )}
              {showCommentNum && (
                <YunxiaoList.Item.Actions width="260px">
                  <div className="commit-list-item-extra-actions-inner-wrap">
                    <div className="commit-list-item-extra-actions-build">
                      {useForList && !noBuildTag && (
                        <BuildsResultTag
                          container={{
                            target: 'commit', // 可选值为 commit 和 merge_request
                            id: commitInfo.id, // commit 或 merge_request 的 id
                          }}
                          projectInfo={projectInfo}
                          isNeedRestart={isNeedRestart}
                          size={'medium'}
                        />
                      )}
                    </div>
                    {commitInfo.commentsCount ? (
                      <div className="commit-list-item-extra-actions-count">
                        <Balloon.Tooltip
                          align="t"
                          trigger={
                            <span
                              className="commit-list-item-extra-actions-count-active"
                              onClick={this.gotoCommitDetailFromCount}
                            >
                              <YunxiaoIcon type="message-line" />
                              <span className="commit-list-item-extra-actions-count-num">
                                {commitInfo.commentsCount > 99 ? '99+' : commitInfo.commentsCount}
                              </span>
                            </span>
                          }
                        >
                          评论数
                        </Balloon.Tooltip>
                      </div>
                    ) : null}
                  </div>
                </YunxiaoList.Item.Actions>
              )}
              <YunxiaoList.Item.Actions>
                {additionalRightItem || null}
                <GpgTag
                  signature={commitInfo.signature}
                  author={{
                    name: commitInfo.committer
                      ? commitInfo.committer.name
                      : commitInfo.committer_name || '',
                    avatarUrl: commitInfo ? commitInfo.avatar_url : '',
                  }}
                />
                <CommitIdAndSrcBtns
                  {...{
                    resourcePath,
                    commitInfo,
                    pathResource,
                    isSrcBtnShow,
                    inCommitDetail: false,
                    trackPage,
                    href: `/${pathResource.fullPath}/commit/${this.props.commitInfo.id}?branch=${branch}`,
                  }}
                />
              </YunxiaoList.Item.Actions>
            </>
          }
        />
      </>
    );
  }
}
